#include "QCoverFaceOperation.h"

#include "FeatureShape/ShapeOperation.h"
#include "FeatureShape/HistoryManager.h"
#include "Core/MainWindow.h"
#include "Core/RWGeometryTool.h"
#include <QMessageBox>

QCoverFaceOperation::QCoverFaceOperation(MainWindow* inMainWindow, ShapeOperation* inOperation, QWidget* parent)
	: QRSWidgetBase(inMainWindow, inOperation, parent)
	, ui(new Ui::QCoverFaceOperationClass())
{
	ui->setupUi(this);

	m_mainWindow->SetCanMultiSelect(false);

	connect(ui->modifyButton, &QPushButton::clicked, this, &QCoverFaceOperation::OnModify);
	connect(ui->confirmButton, &QPushButton::clicked, this, &QCoverFaceOperation::OnConfirm);
	connect(ui->cancelButton, &QPushButton::clicked, this, &QCoverFaceOperation::close);

	connect(m_mainWindow, &MainWindow::OnSelectedActor, this, &QCoverFaceOperation::OnSelectedActor);
}

QCoverFaceOperation::~QCoverFaceOperation()
{
	delete ui;
}

void QCoverFaceOperation::closeEvent(QCloseEvent* event)
{
	disconnect(m_mainWindow, &MainWindow::OnSelectedSubShapes, this, &QCoverFaceOperation::OnSelectedActor);

	m_mainWindow->SubWidgetClose(bIsConfirmed);
	m_mainWindow->SetCanMultiSelect(true);
}

void QCoverFaceOperation::OnSelectedActor(Handle(QIVtkSelectionPipeline) actor)
{
	if (actor)
	{
		m_selectedActor = actor.get();
	}
}

void QCoverFaceOperation::OnModify()
{
	CoverInner();
	m_selectedActor = nullptr;
}

void QCoverFaceOperation::OnConfirm()
{
	CoverInner();
	close();
}

void QCoverFaceOperation::CoverInner()
{
	if (!m_selectedActor)
	{
		QMessageBox::warning(this, tr("Warning"), tr("Please select a valid shape."));
		return;
	}

	TopoDS_Solid solidShape = CloseOpenShellToSolid(m_selectedActor->OccShape());

	if (solidShape.IsNull())
	{
		QMessageBox::warning(this, tr("Warning"), tr("Please select a valid shape."));
		return;
	}

	int shapeIndex = GetIndexFromActor(m_mainWindow->GetCachedActors(), m_selectedActor);

	CoverFaceOperation* op = new CoverFaceOperation(QString("Cover Face"), shapeIndex);
	m_mainWindow->GetHistoryManager()->applyOperation(op);

	m_mainWindow->RemoveActorFromRenderer(m_selectedActor);
	m_mainWindow->createBasicUnitActor(solidShape, true);
}
